from paho.mqtt import client as mqtt_client


class MqttClient:
    def __init__(self, broker, port, client_id, user_name=None, password=None):
        self.broker = broker
        self.port = port
        self.client_id = client_id
        self.client = mqtt_client.Client(client_id=self.client_id)
        self.client.on_connect = self.on_connect
        if user_name and password:
            self.client.username_pw_set(username=user_name, password=password)
        self.client.on_message = self.on_message

    def connect(self):
        self.client.connect(self.broker, self.port)
        self.client.loop_start()

    def disconnect(self):
        self.client.loop_stop()
        self.client.disconnect()

    def publish(self, topic, payload=None, qos=0, retain=False):
        result = self.client.publish(topic, payload=payload, qos=qos, retain=retain)
        return result

    def subscribe(self, topic, qos=0):
        self.client.subscribe(topic, qos)

    def on_connect(self, client, userdata, flags, rc):
        print(f"Connected with result code {rc}")

    def on_message(self, client, userdata, msg):
        print(f"Message received -> {msg.topic}: {str(msg.payload.decode())}")

    def get_client(self):
        return self.client
